package com.luqili.utils.pub.resource;

import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * Jar包静态资源处理工具类
 *
 * @author luqili
 */
public class ResourceJarTool {

    /**
     * 获取当前Jar文件所在的目录
     * <li>非Java包返回环境根目录
     * <li>如: /home/work/git/pub-utils/target/classes
     *
     * @return
     */
    public static String getJarPath() {
        String jarFilePath = ResourceJarTool.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        File jarFile = new File(jarFilePath);
        if (jarFile.isFile()) {
            jarFile = jarFile.getParentFile();
        }
        try {
            return jarFile.getCanonicalPath();
        } catch (IOException e) {
            throw new RuntimeException("获取路径信息异常");
        }
    }

    /**
     * 将静态资源拷贝到根目录
     *
     * @param filePath 如：/config.properties
     */
    public static File copyResourceToRoot(String filePath) {
        return copyResourceToRoot(filePath, false);
    }

    /**
     * 将静态资源拷贝到根目录
     *
     * @param filePath   如：/config.properties
     * @param delOldFile 是否删除已存在的文件
     * @return
     */
    public static File copyResourceToRoot(String filePath, boolean delOldFile) {
        String rootPath = getJarPath();
        File resourceFile = new File(rootPath + filePath);
        if (delOldFile && resourceFile.exists()) {
            resourceFile.delete();
        }
        if (!resourceFile.exists()) {
            resourceFile.getParentFile().mkdirs();
            try (InputStream in = ResourceJarTool.class.getResourceAsStream(filePath); OutputStream out = new FileOutputStream(resourceFile)) {
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("读取内置静态文件异常,文件:" + filePath + "\n" + e.getMessage());
            }
        }
        if (delOldFile) {
            resourceFile.deleteOnExit();
        }
        return resourceFile;
    }

    /**
     * 将静态资源拷贝到根目录
     *
     * @param filePath
     * @return
     */
    public static String copyResourceToRootToString(String filePath) {
        return copyResourceToRootToString(filePath, false);
    }

    /**
     * 将静态资源拷贝到根目录
     *
     * @param filePath
     * @param delOldFile 是否删除已存在的文件
     * @return
     */
    public static String copyResourceToRootToString(String filePath, boolean delOldFile) {
        File file = copyResourceToRoot(filePath, delOldFile);
        try {
            return file.getCanonicalPath();
        } catch (IOException e) {
            throw new RuntimeException("获取路径信息异常:" + filePath);
        }

    }

}
